// 背景包装
exports.init = init;
exports.getBackgroundSprite = getBackgroundSprite;
exports.ticker = ticker;

const PIXI = require("pixi.js");

const GRASS_RESOURCE = "resources/bg_grass.jpg";


const PLAYER = require("./player");
const player = PLAYER.player;

const background = {
    xBound: 0,
    yBound: 0,
    isOnXBound: true,
    isOnYBound: true,
}

/**
 * @type {PIXI.ParticleContainer}
 */
var backgroundSprite = undefined;

/**
 * @returns {PIXI.ParticleContainer}
 */
function getBackgroundSprite() {
    return backgroundSprite;
}

// 初始化背景
/** 
 * @param {PIXI.Application} app
 */
function init(app) {
    console.log("背景加载");
    // 初始化了
    // 设置容器
    backgroundSprite = new PIXI.ParticleContainer(10000);
    // 加载图片
    let grassTexture = PIXI.Loader.shared.resources[GRASS_RESOURCE].texture;
    for (let i = 0; i < 100; i++) {
        for (let j = 0; j < 100; j++) {
            let grassSprite = new PIXI.Sprite(grassTexture);
            grassSprite.width = 100;
            grassSprite.height = 100;
            grassSprite.x = j * 100 + 10;
            grassSprite.y = i * 100 + 10;
            backgroundSprite.addChild(grassSprite);
        }
    }
    // 初始化边界数据
    background.xBound = -(100 * 100 - app.screen.width);
    background.yBound = -(100 * 100 - app.screen.height);


    app.stage.addChild(backgroundSprite);
}

// 背景循环
function ticker() {
    // 是否在x边界
    function isOnXBound(tmp) {
        return tmp > 0 || tmp < background.xBound;
    }
    // 是否在y边界
    function isOnYBound(tmp) {
        return tmp > 0 || tmp < background.yBound;
    }

    if (player.isOnCenter) {
        // 检查边界
        let tmp = backgroundSprite.x - player.nowXSpeed;
        if (!isOnXBound(tmp)) {
            backgroundSprite.x = tmp;
            background.isOnXBound = false;
        } else {
            background.isOnXBound = true;
        }
        tmp = backgroundSprite.y - player.nowYSpeed;
        if (!isOnYBound(tmp)) {
            backgroundSprite.y = tmp;
            background.isOnYBound = false;
        } else {
            background.isOnYBound = true;
        }
    }


}